<template>
  <div class="goods_info_spec">
    <div class="spec_list" v-for="(v, k) in goods.specList" :key="k">
      <span>{{ v.name }}</span>
      <ul>
        <li
          :class="{ red: isSelected(v, index) }"
          v-for="(val, index) in v.specValue"
          :key="index"
          @click="toggleSelection(v, index)"
        >
          {{ val.name }}
        </li>
      </ul>
    </div>
  </div>
</template>

<script setup lang="ts">
import { reactive } from 'vue';

const selectedSpecs = reactive<Record<string, string>>({});
const emit = defineEmits(['change']);
const props = defineProps({
  goods: {
    type: Object as () => { skus: any[]; specList: any[] },
    default: () => ({ skus: [], specList: [] })
  }
});

/* 属性选择 */
const toggleSelection = (spec: any, value: string) => {
  const key = spec.id;
  if (selectedSpecs[key] === value) {
    delete selectedSpecs[key];
  } else {
    selectedSpecs[key] = value;

    // 检查是否所有规格都已选择
    const allSpecsSelected = props.goods.specList.every((s) => selectedSpecs[s.id] !== undefined);
    if (allSpecsSelected) {
      // 如果所有规格都已选择，则查找匹配的 SKU
      const selectedSku = props.goods.skus.find((sku) => {
        // 假设 sku.specIds 是一个对象，键为规格ID，值为选中的值
        return Object.keys(sku.specId).every((specId) => {
          return sku.specId[specId] === selectedSpecs[specId];
        });
      });
      if (selectedSku) {
        emit('change', {
          id: selectedSku.id,
          name: selectedSku.name,
          imgUrl: selectedSku.imgUrl,
          price: selectedSku.price,
          oldPrice: selectedSku.oldPrice
        });
      }
    }
  }
};

const isSelected = (spec: any, value: string) => {
  const key = spec.id;
  return selectedSpecs[key] === value;
};
</script>

<style scoped lang="scss">
.goods_info_spec {
  margin-top: 20px;
  padding-left: 10px;
  line-height: 20px;
  color: #666;
  position: relative;
  z-index: 200;

  .spec_list {
    margin-bottom: 10px;

    span {
      float: left;
      width: 84px;
    }

    ul {
      float: left;

      li {
        cursor: pointer;
        float: left;
        color: #666;
        border: 1px solid #e1e1e1;
        border-radius: 2px;
        font-size: 12px;
        padding: 0 8px;
        margin-right: 10px;
      }

      li.red {
        border: 1px solid #ca151e;
        color: #ca151e;
      }

      li:hover {
        border: 1px solid #ca151e;
        color: #ca151e;
      }
    }
  }

  :after {
    content: '';
    display: block;
    clear: both;
  }
}
</style>
